
import { EventName } from "../const/eventName";
import { App } from "../../../src/app";
import { SingletonClass } from "./singletonClass";

/**
 * 全局定时器管理
 */
export default class TimeManager extends SingletonClass<TimeManager> {

    public readonly TimeDownConst: number = 300;
    public TimeDown: number = 0;
    private count_down_id: number = 0;
    private _isDoing: boolean = true;

    constructor() {
        super();
    }

    protected onInit(): void {
        this.TimeDown = 0;
        this.count_down_id = 0;
    }

    /** 全局计时器，每秒一次,只执行加、减，不加多余逻辑 */
    private updateSecound() {
        if (!this._isDoing) return;
        this.TimeDown -= 1;
        App.event.emit(EventName.Game.TIMER_DOWN, this.TimeDown);
    }

    public start() {
        console.log('开启全局时间倒计时');
        this.TimeDown = this.TimeDownConst;
        this._isDoing = true;
        this.count_down_id = setInterval(this.updateSecound.bind(this), 1000);
    }

    public stop() {
        this._isDoing = false;
        clearInterval(this.count_down_id);
    }

    public reStart() {
        this._isDoing = false;
        clearInterval(this.count_down_id);
        this.TimeDown = this.TimeDownConst;
        this.count_down_id = setInterval(this.updateSecound.bind(this), 1000);
    }

    public pause() {
        this._isDoing = false;
    }

    public resume() {
        this._isDoing = true;
    }
}
